package com.gennlife.dataformat.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.gennlife.common.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

@Controller
@RequestMapping("htmlTable")
public class HtmlTableController {
    private static final Logger logger = LoggerFactory.getLogger(HtmlTableController.class);
    private static String FILE_BASE_PATH = ResourceBundle.getBundle("htmlTable").getString("file.base.path");
    private static String[] TABLE_NAMES = ResourceBundle.getBundle("htmlTable").getString("table.name").split(",");
    private static String TABLE_HEADS = ResourceBundle.getBundle("htmlTable").getString("table.head");
    private static String TABLE_NAME_START = ResourceBundle.getBundle("htmlTable").getString("table.name.start");
    private static String[] TABLE_NAME_ENDS = ResourceBundle.getBundle("htmlTable").getString("table.name.end").split(",");

    //解析数据
    @ResponseBody
    @RequestMapping("/resolveData")
    public String resolveData() throws Exception {
        //BufferedReader是可以按行读取文件
        String path = FILE_BASE_PATH + "/txt/";
        FileInputStream inputStream;
        BufferedReader bufferedReader;
        File file = new File(path);
        if (file != null) {
            File[] f = file.listFiles();
            if (f != null) {
                for (int i = 0; i < f.length; i++) {
                    inputStream = new FileInputStream(f[i]);
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String str;
                    JSONObject json = new JSONObject();
                    while ((str = bufferedReader.readLine()) != null) {
                        if (!str.startsWith("document_sn")) {
                            json = rsHtmlTable(str, json);
                        }
                    }
                    //close
                    inputStream.close();
                    bufferedReader.close();
                    //遍历结果
                    if (json != null) {
                        for (Map.Entry entry : json.entrySet()) {
                            insertExcel((String) entry.getKey(), (List<List<String>>) entry.getValue());
                        }
                    }
                }
            }
        }
        return "SUCCESS";
    }


    private JSONObject rsHtmlTable(String line, JSONObject json) {
        List<String> tempData = new ArrayList<>();
        String[] lineParams = line.split("@ge");
        if (lineParams.length < 12) {
            return null;
        }
        tempData.add(lineParams[0]);
        tempData.add(lineParams[1]);
        tempData.add(lineParams[3]);
        Document doc = Jsoup.parse(lineParams[11]);
        Elements rows;
        try {
            rows = doc.select("table").get(1).select("tr");
        } catch (IndexOutOfBoundsException e) {
            rows = doc.select("table").get(0).select("tr");
        }
        List<List<String>> data = new ArrayList<>();
        String fileName = "";

        Element row;
        Elements tds;
        String text;
        int index;
        for (int i = 0; i < rows.size(); i++) {
            row = rows.get(i);
            tds = row.select("td");
            text = "";
            for (int j = 0; j < tds.size(); j++) {
                text = tds.get(j).text();
                if (isFileName(text)) {
                    for (String tableExcel : TABLE_NAMES) {
                        if (text.replaceAll(TABLE_NAME_START, "").equals(tableExcel)) {
                            fileName = tableExcel;
                        }
                    }
                }
                index = text.replaceAll(":", "：").indexOf("：") + 1;
                if (StringUtils.isNotBlank(text) && index > 0 &&
                        TABLE_HEADS.indexOf(text.replaceAll(":", "：").substring(0, index)) > -1
                        && text.substring(index).indexOf("：") == -1 && text.substring(index).indexOf(":") == -1) {
                    if (index < text.length()) {
                        tempData.add(text.substring(index));
                    } else {
                        tempData.add(tds.get(j + 1).text());
                    }
                }

                if (i == rows.size() - 1 && !tds.get(j).attr("hidden").equals("true")
                        && !tds.get(j).attr("hidden").equals("ture")) {
                    tempData.add(text);
                }
            }
        }
        data.add(tempData);
        if (StringUtils.isBlank(fileName)) {
            logger.error(line);
            return null;
        } else if (json.get(fileName) != null) {
            List<List<String>> existData = (List<List<String>>) json.get(fileName);
            existData.addAll(data);
            json.put(fileName, existData);
        } else {
            json.put(fileName, data);
        }
        return json;
    }

    private static boolean isFileName(String text) {
        boolean isFileName = false;
        for (String end : TABLE_NAME_ENDS) {
            if (text.endsWith(end)) {
                isFileName = true;
                break;
            }
        }
        return isFileName;
    }

    private static void insertExcel(String fileName, List<List<String>> data) throws FileNotFoundException {
        InputStream inputStream = new FileInputStream(FILE_BASE_PATH + "/base/" + fileName + ".xlsx");
        OutputStream out = new FileOutputStream(FILE_BASE_PATH + "/result/" + fileName + ".xlsx");
        ExcelWriter writer = EasyExcelFactory.getWriterWithTemp(inputStream, out, ExcelTypeEnum.XLSX, true);
        //写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
        Sheet sheet1 = new Sheet(1);
        writer.write0(data, sheet1);
        writer.finish();
    }

}
